package com.jokins.admin.vue.hefeng.action;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jokins.admin.vue.hefeng.actioncontext.GetCityListDoc;
import com.jokins.admin.vue.hefeng.mapper.CityMapper;
import com.jokins.admin.vue.hefeng.param.CityParam;
import com.jokins.admin.vue.hefeng.utils.FetchCityDataFromExternal;
import com.jokins.admin.vue.hefeng.vo.CityListVo;
import com.jokins.common.actions.action.ActionContext;
import com.jokins.common.actions.action.BaseAction;
import com.jokins.common.actions.exception.BusinessException;
import com.jokins.common.config.CustomCacheManager;
import com.jokins.common.entry.hefeng.City;
import com.jokins.common.util.SqlTypeConverter;
import com.jokins.common.util.date.DateFormatter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Slf4j
@Component
public class GetCityListDocAction extends BaseAction<GetCityListDoc> {

    @Autowired
    CityMapper cityMapper;
    @Autowired
    private CustomCacheManager cacheManager;

    @Override
    protected void process(GetCityListDoc actionContext) throws BusinessException {
        CityParam param = actionContext.getParam();
        log.info("进入GetCityListDocAction。。。。。");
        String cityName = param.getCityName();
        log.info("Executing GetApplyList SQL query...");
        QueryWrapper<City> queryWrapper = new QueryWrapper<>();
        Optional.ofNullable(cityName)
                .filter(name -> !name.isEmpty())
                .ifPresent(name -> queryWrapper.like("LOWER(name)", cityName.toLowerCase())
                        .or()
                        .like("LOWER(abbreviation)", cityName.toLowerCase()));
        List<City> cityList = cityMapper.selectList(queryWrapper);
        if (cityList.isEmpty()) {
            cityList = FetchCityDataFromExternal.API(cityName);
            log.info("从外部API获取城市列表:{}", cityList);
            cityMapper.saveList(cityList);
            // 在数据写入后刷新缓存
            cacheManager.cacheManager();
            cityList = cityMapper.selectList(queryWrapper);
        }
        List<CityListVo> cityListVos = cityList.stream()
                .map(city -> {
                    CityListVo vo = new CityListVo();
                    SqlTypeConverter.convertEntity(city, vo, DateFormatter.DATE_FORMAT_YYYY_MM_DD_HH_MM_SS);
                    return vo;
                })
                .collect(Collectors.toList());
        log.info("cityVoList:{}", JSON.toJSONString(cityListVos));
        actionContext.setResult(ActionContext.RESULT_DOC_KEY, cityListVos);
    }
}
